package com.aruba.flowapplyapplication.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aruba.flowapplyapplication.model.Article
import com.aruba.flowapplyapplication.net.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

/**
 * Created by aruba on 2021/9/21.
 */
class ArticleViewModel : ViewModel() {
    var searchText: MutableLiveData<String> = MutableLiveData()
    var articleList = MutableLiveData<List<Article>>()

    fun getArticle() {
        if (searchText.value == null) return
        
        viewModelScope.launch {
            flow {
                emit(RetrofitClient.getApi().searchArticles(searchText.value!!))
            }.flowOn(Dispatchers.IO).catch { e ->
                e.printStackTrace()
            }.collect {
                articleList.value = it
            }
        }
    }
}